package com.itheima.service.impl;

import com.itheima.bean.User;
import com.itheima.dto.UserDTO;
import com.itheima.exception.LoginFailedException;
import com.itheima.mapper.UserMapper;
import com.itheima.service.UserService;
import com.itheima.utils.JwtUtil;
import com.itheima.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.security.auth.login.AccountLockedException;

@Service
public class UserServiceImpl  implements UserService {

    @Autowired
    private UserMapper userMapper;
    /**
     * 用戶登录
     *
     * @param userDTO
     * @return
     */
    @Override
    public User login(UserDTO userDTO) {
        //登录校验
        User user = new User();
        user.setUsername(userDTO.getUsername());
        //对密码进行校验
        String password = userDTO.getPassword();
        //进行md5加密
        password  = DigestUtils.md5DigestAsHex(password.getBytes());
        //根据用户名查询数据库User表
        User u = userMapper.getBy(user);
        if(u == null) {
            throw new LoginFailedException("用户不存在");
        }
        //校验密码
       if(!u.getPassword().equals(password)) {
           //如果密码不相同
           throw new LoginFailedException("密码错误");
       }
        if (u.getStatus() == 0) {
            //账号被锁定
            throw new LoginFailedException("账号被禁用");
        }
       //登录成功
        return u;
    }
}
